/**
 * Created with JetBrains PhpStorm.
 * User: cgp
 * Date: 13-10-22
 * Time: 下午5:31
 * register
 */
var submitFlag = false;
var reg = {
    timer: undefined,
    request_url: 'call/jh_mem.php',
    getToken : function(){
        return $("input#csrf_token").val();
    },
    sendVcode:function(){
        var that = $(this),
            mobile = verify.chkMobile(),
            token  = reg.getToken(),
            email  = verify.chkEmail(),
            request_data  = {
                action:'SendVcode',
                token:token,
                mobile:mobile,
                email :email,
                stype:'register'
            };
        $.post(reg.request_url,request_data,'','json')
            .done(function(json_res){
                if(json_res.status=='ok') {
                    $("#sendRes").text('验证码已发送');
                    that.attr('disabled','disabled').text('重新发送验证码');
                    $("#resendCodeWait").show();
                    var countDown = function(){
                        t-=1;
                        $("#countDown").text(t);
                        if(t<=0){
                            clearInterval(reg.timer);
                            that.removeAttr('disabled');
                            $("#resendCodeWait").hide();
                        }
                    };
                    var t= 60;
                    reg.timer = setInterval(countDown, 1000);
                } else {
                    $("#sendRes").text(json_res.msg);
                }
            });
    },
    showLicense : function(){
        if($(this).val()=='旅行社') {
            $("#license_no_tr").show();
        } else {
            $("#license_no_tr").hide();
        }
    },
    submitRegister : function(){
        var requiredFileds = $("input.required"),
            len = requiredFileds.length,
            subFlag = false;
        for(var i=0;i<len;i++) {
            if( requiredFileds[i].value=='' ) {
                requiredFileds[i].focus();
                var tab3 = getTab3($(requiredFileds[i]));
                tab3[1].show();
                return false;
            }
            subFlag = true;
        }
        if( !subFlag || $("p.error:visible").length>0) {
            return false;
        }

        var actionType = $("input[name='actionType']").val(),
		
		
            post_data = $("form#reg_form").serialize();
			// alert(actionType);
		// return false;
        $.post(reg.request_url,post_data,'','json')
            .done(function(json_result){
                if(json_result.status=='ok') {
                    if(actionType=='register') {
                        buildAutoSubmitForm('register_u_step3.html',json_result);
                    }
                    else {
                        alert(json_result.msg);
                        location.reload();
                    }
                } else {
                    alert(json_result.msg);
                }
            });
    },

    forgetPassVerify : function(){
        var passport = $("input[name='forget_username']").val();
        if(!passport || passport.length<4) {
            return false;
        }
        var request_data = {
            action:"ChkPassport",
            mobile:passport,
            token: reg.getToken(),
            stype: 'forget'
        };
        //console.log(request_data);
        $.getJSON(reg.request_url, request_data)
            .done(function(res){
                $("span.grwod")[0].innerHTML = res.msg;
                if(res.status=='ok') {
                    request_data['action'] = 'SendVcode';
                    request_data['stype'] = 'forget';
                    request_data['mobile'] = res.mobile;
                    $.getJSON(reg.request_url,request_data)
                        .done(function(res){
                            if(res.status=='ok') {
                                buildAutoSubmitForm('forget_u_mobile.html', {passport:passport});
                            }
                        });
                }
            });
    },
    forgetCodeVerify : function(){
        var passport = $("#passport").text(),
            vcode = $("input[name='v_code']").val();
        $.getJSON(reg.request_url,{action:'VerifyVcode', mobile:passport,vcode:vcode})
            .done(function(res){
                if(res.status=='ok'){
                    buildAutoSubmitForm('forget_u_reset.html',{passport:passport});
                }
                else{
                    $("span.grwod")[0].innerHTML = "不存在此验证码！请重新输入";
                }
            });
    },
    forgetResetPwd : function() {
        if(!verify.passwordVerify() || !verify.passwordConfirm()) {
            return false;
        }
        var passport = $('input[name="passport"]').val(),
            pass1 = $("input[name='password']").val(),
            pass2 = $("input[name='confirmPwd']").val(),
            request_data = {
                action:"ResetPassword",
                passport:passport,
                pass1 : pass1,
                pass2 : pass2,
                stype: 'resetpwd'
        };
        if( !passport ) {
            alert('账号不正确');
            return false;
        }
        $.post(reg.request_url,request_data,function(json_data){
            if(json_data.status=='ok') {
                buildAutoSubmitForm('forget_u_ok.html',{},'hide_frm','GET');
            } else {
                alert(json_data.msg);
            }
        },'json');
    }
};
var verify = {
    is_chinese : function(str) {
       // var  reg_zh = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
		var  reg_zh=/^[\u4e00-\u9fa5]+$/;
        return reg_zh.test(str);
    },
    is_email : function(email){
        if(email.length>6) {
            var emailReg = /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/;
            var re = new RegExp(emailReg);
            return re.test(email);
        }
        return false;
    },
    chkMobile : function(){
        var m = $("input[name='mobile']").val();
        if( checkMobileNum(m) ) {
            return m;
        }
        return false;
    },
    chkEmail : function() {
        var email = $("input[name='email']").val();
        if (verify.is_email(email)) {
            return email;
        }
        return false;
    },
    unameVerify : function(){
        var un = $(this).val(),
            tab3 = getTab3($(this)),
            len=un.length;
        if(!len) {
            return;
        }
        tab3[4].hide();
        if(len>1 && verify.is_chinese(un)) {
            tab3[3].show();
        }  else {
            tab3[2].show().text('姓名必须为中文汉字');
        }
    },
    verifyVcode : function(){
        var vcode = $(this).val(), tab3 = getTab3($(this));
        if(!vcode || vcode.length<6) {
            return false;
        }
        $.getJSON(reg.request_url, {action:'VerifyVcode',vcode:vcode})
            .done(function(res){
                tab3[1].hide();
                if(res.status=='ok') {
                    tab3[3].show();
                } else {
                    tab3[2].text(res.msg).show();
                }
            });
    },
    verifyAlipay: function(){
        var ap = $(this).val(),tab3 = getTab3($(this));
        /*2015-03-31 注册时不再必须输入支付宝 但输入了就一定要是手机号或者邮箱
        if(!ap) {
            return false;
        }
        tab3[4].hide();
        */
        if(!ap || (verify.is_email(ap) || checkMobileNum(ap))) {
            tab3[3].show();
        } else {
            tab3[2].show().text('请输入正确的支付宝账号（手机号或邮箱格式）');
        }
    },
    chkPhone : function(){
        var tab3 = getTab3($(this)),
            phoneNum = $(this).val();
        tab3[1].hide();
        if( phoneNum!='') {
            if(  ! checkPhone(phoneNum) ) {
                tab3[2].text('固话格式错误。正确格式为xxxx-xxxxxxx').show();
                return false;
            }
            tab3[3].show();
        }
        return true;
    },
    chkVcode : function(){
        var vcode = $("input#yminput").val(),
            mobile = reg.chkMobile();
        if(!mobile) {
            alert('请输入正确的手机号！');
            return false;
        }
        var request_data = {
            action:'VerifyVcode',
            token : reg.getToken(),
            vcode:vcode,
            mobile:mobile
        };
        $.getJSON(reg.request_url,request_data)
            .done(function(res){
                if(res.status!='ok'){
                    $("#ymicon").addClass('error').text('验证码不存在');
                }
                else {
                    buildAutoSubmitForm('register_u_step2.html',{mobile:mobile})
                }
            });
    },
    mobileVerify : function() {
        var tab3 = getTab3($(this)),
            mobile = $("input[name='mobile']").val();
        if(mobile=='') {
            return false;
        }
        tab3[4].hide();
        if(!checkMobileNum(mobile) ) {
            tab3[2].text('手机号格式错误').show();
             $("#sendVcodeBtn").attr('disabled','disabled')
                .removeClass('ui-button-sorange')
                .addClass('ui-button-swhite');
            return false;
        }
        $.getJSON(reg.request_url,{action:'chkAndGetReg', mobile:mobile})
            .done(function(json_res){
                if(json_res.ajaxStatus==2){
                    tab3[2].text('该手机号已经存在，请重新输入').show();
					tab3[3].hide();
                    $('input[name="sanke"]').val('0');
                    if( $("#sendVcodeBtn").hasClass('ui-button-sorange') ) {
                        $("#sendVcodeBtn").attr('disabled','disabled')
                            .removeClass('ui-button-sorange')
                            .addClass('ui-button-swhite');
                    }
					//是否已经列出
					flag=false;
					$("#selected_show_list tr").each(function(els,index){
						if($(this).attr("id")=="dist_"+json_res.id){
							flag=true;return false;
						}
					});
					if(flag) return false;
					tr=$("#selected_distor_list").html();
					tr=tr.replace(/{\$id}/g,json_res.id);
					tr=tr.replace(/{\$dname}/g,json_res.dname);
					tr=tr.replace(/{\$com_type}/g,json_res.com_type);
					tr=tr.replace(/{\$account}/,json_res.passport);
					tr=tr.replace(/{\$cname}/,json_res.cname);
					tr=tr.replace(/{\$mobile}/,json_res.mobile);
					if(json_res.created==1){
						var str='';
						str='已添加|<a target="_blank" href="priceset.html?did='+json_res.id+'">价格配置</a>';
					}else{
						str='<a href="javascript:" class="selected_distor_add" data-id="'+json_res.id+'">添加</a>';
					}
					tr=tr.replace(/{\$btn}/,str);
					$("#selected_show_list").append(tr);
                }else if(json_res.ajaxStatus==3) {
                    tab3[2].text('该手机号已经存在，请重新输入').show();
					tab3[3].hide();
                    $('input[name="sanke"]').val('0');
                    $("#sendVcodeBtn").attr('disabled','disabled');
                } else if(json_res.ajaxStatus==4) {
					submitFlag = true;
                    tab3[3].show();
                    $('input[name="sanke"]').val('1');
                    $("#sendVcodeBtn").removeAttr('disabled')
                        .removeClass('ui-button-swhite')
                        .addClass('ui-button-sorange');
				}else {
					submitFlag = true;
                    tab3[3].show();
                    $('input[name="sanke"]').val('0');
                    $("#sendVcodeBtn").removeAttr('disabled')
                        .removeClass('ui-button-swhite')
                        .addClass('ui-button-sorange');
				}
            });
    },
    passwordVerify: function(){
        var elem = $("input[name='password']"),
            password = elem.val(),
            tab3 = getTab3(elem),
            tip = tab3[2],//$("#pwd_msg"),
            flag = false,
            len = password.length,
            strength = 0;
        if(len==0){
            return;
        } else if(len>0 && len<6 ){
            tip.text("请输入大于等于6位数的密码");
            strength = 0;
        } else if(len>20){
            tip.text("密码过长");
            //return false;
        } else if(password.match(/\s/)){
            tip.text("密码仅支持英文、数字和字符，不支持空格");
            // return false;
        } else {
            flag = true;
            var pwd_strength=$("#password_strength");

        }
        tab3[4].hide();
        if(!flag) {
            tab3[2].show();
        } else {
            tab3[3].show();
        }
        submitFlag = flag;
        return flag;
    },
    pwdStrength : function(){
        $("tr#pwd_strength").show();
        var strength = 0,
            password = $(this).val(),
            pwlevel = $("#pwlevel"),
            pwlevel2 = $("#pwlevel2");
        if(password.match(/([a-z]+)/)) {
            strength++;
        }
        if(password.match(/([A-Z]+)/)) {
            strength++;
        }
        if(password.match(/([0-9]+)/)) {
            strength++;
        }
        if(password.match(/(\W+)/)) {// 非任意(文字和数字)字母和下滑线的字符
            strength++;
        }
        if (password.length< 8){
            strength--;// 密码的长度
        }else{
            strength++;
        }
        switch(strength) {
            case 0:
            case 1:
                pwlevel.css('width','35%');
                pwlevel2.text('弱');
                break;
            case 2:
            case 3:
                pwlevel.css('width','75%');
                pwlevel2.text('中');
                break;
            case 4:
            case 5:
                pwlevel.css('width','100%');
                pwlevel2.text('强');
                break;
            default:
                pwlevel.css('width','0');
                pwlevel2.text('');
                break;
        }
    },
    passwordConfirm:function() {
        var elem = $("input[name='confirmPwd']")
            tab3 = getTab3($(this)),
            flag = false,
            n = $("input[name='password']")[0],
            d = $("input[name='confirmPwd']")[0];
        if(d.value=='') {
            return false;
        }
        if( n.value!=d.value ){
            tab3[2].text("两次输入的密码不一致，请重新输入");
        } else {
            flag = true;
            tab3[2].text("");
        }
        tab3[4].hide();
        if(!flag) {
            tab3[2].show();
        } else {
            tab3[3].show();
        }
        submitFlag = flag;
        return flag;
    },
    companyVerify : function(){
        var cname = $(this).val(),tab3 = getTab3($(this));
        if(!cname) {
            return;
        }
        tab3[4].hide();
		//verify.is_chinese(cname) &&
        if(  cname.length>=2 ) {
            tab3[3].show();
        } else {
            tab3[2].show().text('公司名为中文汉字');
        }
		$.getJSON(reg.request_url,{action:'chkDname', dname:cname})
            .done(function(json_res){
                if(json_res.status=='ok' ){
                    tab3[2].text('公司名已存在').show();
					tab3[3].hide();
                    if( $("#sendVcodeBtn").hasClass('ui-button-sorange') ) {
                        $("#sendVcodeBtn").attr('disabled','disabled')
                            .removeClass('ui-button-sorange')
                            .addClass('ui-button-swhite');
                    }
                }
                else {
                    submitFlag = true;
                    tab3[3].show();
					tab3[2].hide();
                    $("#sendVcodeBtn").removeAttr('disabled')
                        .removeClass('ui-button-swhite')
                        .addClass('ui-button-sorange');
                }
            });
    },
	
	allianceVerify : function(){
        var cname = $(this).val(),tab3 = getTab3($(this));
        if(!cname) {
            return;
        }
        tab3[4].hide();
		//verify.is_chinese(cname) &&
        if(  cname.length>=2 ) {
            tab3[3].show();
        } else {
            tab3[2].show().text('公司名为中文汉字');
        }
		$.getJSON(reg.request_url,{action:'chkDname', dname:cname})
            .done(function(json_res){
                if(json_res.status=='ok' ){
                    tab3[2].text('公司名已存在').show();
					tab3[3].hide();
                    if( $("#sendVcodeBtn").hasClass('ui-button-sorange') ) {
                        $("#sendVcodeBtn").attr('disabled','disabled')
                            .removeClass('ui-button-sorange')
                            .addClass('ui-button-swhite');
                    }
                }
                else {
                    submitFlag = true;
                    tab3[3].show();
					tab3[2].hide();
                    $("#sendVcodeBtn").removeAttr('disabled')
                        .removeClass('ui-button-swhite')
                        .addClass('ui-button-sorange');
                }
            });
    },
    qqVerify : function() {
        var qq=$(this).val(),tab3 = getTab3($(this));
        if(!qq) {
            return;
        }
        tab3[4].hide();
        if(isNaN(qq)) {
            tab3[2].text('QQ号必须为数字').show();
        }
        else {
            tab3[3].show();
        }
    },
    emailVerify:function(){
        var email=$(this).val(),tab3 = getTab3($(this));
        if(!email) {
            return;
        }
        tab3[4].hide();
        if( !verify.is_email(email) ) {
            tab3[2].text('邮箱格式不正确').show();
        }
        else {
            tab3[3].show();
        }
    }
};

jQuery(document).ready(function($){

    $("input.ui-input").on('focus', function(){
        var tab3 =  $(this).parents('tr').find('td.tab3');
        tab3.find('p.error').hide();
        if($(this).val()!='' && tab3.find('p:visible').length) {
            return;
        }
        tab3.find('p.normal').show();
        tab3.find('p.ok').hide();
    });
    $("input.ui-input").on('blur', function(){
        $(this).parent('td').next('td.tab3').find('p.normal').hide();
    });

    $("input[name='dtype']").on('click', function(){
        var dt = parseInt($(this).val());
        $(".dtlist").hide();
        $("tr#license_no_tr").hide();
        if(!dt) {
            $("#alipay_req").show().addClass('required');
            $("#dt0").show();
        } else {
            $("#alipay_req").hide().removeClass('required');
            $("#dt1").show();
        }
    });


    //注册BEGIN
    if($("#area").length){
        var area,pro_id, city_id,countr_id;
        if($("input[name='area']").val()){
            area = $("input[name='area']").val().split('|'),
                por_id = area[0],city_id = area[1],country_id = area[2];
        } else {
            por_id = 12,city_id = 381,country_id = 0;
        }
        $("#area").getAreas({update:true,pro_id:por_id,city_id:city_id,county_id:country_id});
    }

    $("input[name='mobile']").on('keyup blur',verify.mobileVerify);
    $("input[name='username']").on('blur',  verify.unameVerify);
    $("input[name='vcode']").on('keyup',  verify.verifyVcode);
    $("input[name='password']").on('keyup',  verify.pwdStrength);
    $("input[name='password']").on('blur',  verify.passwordVerify);
    $("input[name='confirmPwd']").on('keyup blur', verify.passwordConfirm);
    $("input[name='alipay']").on('blur',  verify.verifyAlipay);
    $("input[name='company']").on('blur', verify.companyVerify);
    $("input[name='alliance']").on('blur', verify.allianceVerify);
    $("input[name='qq']").on('blur', verify.qqVerify);

    if ($("input[name='email']").length) {
        $("input[name='email']").on('blur', verify.emailVerify);

    }

    $("select.dtlist").on('change', reg.showLicense)
    $("#sendVcodeBtn").on('click', reg.sendVcode);
    $("#verifySubmit").on('click', reg.chkVcode);
    $("#resendCode").on('click', reg.sendVcode);

    //用户注册-提交信息
    $("#submit_step2").on('click', reg.submitRegister);

    //注册end

    //忘记密码BEGIN
    $("input#forget_submit1").on('click', reg.forgetPassVerify);
    $("input#forget_submit2").on('click',reg.forgetCodeVerify);
    $("input#forget_submit3").on('click',reg.forgetResetPwd);
    //忘记密码END

    //添加分销商
    $("#distor_choice").on('click', 'li', function(){
        var type = $(this).attr('data-type');
        $(this).addClass('ui-tab-item-current')
            .siblings('li').removeClass('ui-tab-item-current');
        if(type=='create') {
            $("#create_new").show();
            $("#select_old").hide();
        } else if(type=='select') {
            $("#create_new").hide();
            $("#select_old").show();
        }
    });
	
	/*
    $("#dname_c").on('blur', function(){
        var elem = $(this),
            tab3 = getTab3($(this));
        //var chkExist = function(mem_list) {
            //console.log(mem_list);
            tab3[4].hide();
            //if( mem_list.status=='ok' ) {
			if (!$(this).attr("value")){
                //tab3[2].text('该分销商已经存在，请修改分销商名称或“选择已有分销商”').show();
                tab3[2].text('请填写姓名').show();
            } else {
                tab3[3].show();
            }
       // }
        //getDistorList(elem, tab3, chkExist);
    });

    $("#mobile_c").on('blur', function(){
        var elem = $(this),
            tab3 = getTab3($(this));
        //var chkExist = function(mem_list) {
            //console.log(mem_list);
            tab3[4].hide();
            //if( mem_list.status=='ok' ) {
			if (!$(this).attr("value")){
                //tab3[2].text('该分销商已经存在，请修改分销商名称或“选择已有分销商”').show();
                tab3[2].text('请填写手机号').show();
            } else {
                tab3[3].show();
            }
       // }
       // getDistorList(elem, tab3, chkExist);
    });
	*/
    $("input[name='g_tel']").on('blur', verify.chkPhone);
    $("#distor_btn_c").on('click', reg.submitRegister);
});
function buildAutoSubmitForm(action, values, frmid, method) {
    var method = method || 'post',
        frmid = frmid || 'auto_submit_frm',hiddens='';
    for(var name in values) {
        hiddens += '<input type="hidden" name="'
            +name+'" value="'+values[name]+'"/>';
    }
    var form = '<form id="'+frmid+'" action="'+action+'" method="'+method+'">'
        +hiddens+'</form>';
    $("body").append(form);
    $("#"+frmid).submit();
}

function getDistorList(elem, tab3, callback) {
    var dname = $.trim(elem.val()),
        mode  = elem[0].id=='dname_c' ? 1: 0;

    if(dname.length<2 ) {
        return false;
    }
    else if( ! verify.is_chinese(dname) ) {
        tab3[1].hide();
        tab3[2].text('分销商名称仅限大于两个汉字的中文').show();
        return false;
    }
    else {
        tab3[2].hide();
    }
    var request_data = {
        action : 'SearchDistor',
        token: reg.getToken(),
        dname : dname,
        mode : mode
    };
    $.getJSON(reg.request_url, request_data)
        .done(function(json_data){
            callback(json_data);
        });
}

function getTab3(elem) {
    var tab3 = elem.parents('tr').find('td.tab3'),
        p = tab3.find('p'),
        error = tab3.find('p.error'),
        ok = tab3.find('p.ok'),
        normal = tab3.find('p.normal');
    return [tab3,normal,error,ok,p];
}


function bitTotal(num){
    var modes=0;
    for (var i=0;i<4;i++){
        if (num & 1) modes++;
        num>>>=1;
    }
    return modes;
}

function CharMode(iN){
    if(iN>=48 && iN <=57) //数字
        return 1;
    if(iN>=65 && iN <=90) //大写
        return 2;
    if(iN>=97 && iN <=122) //小写
        return 4;
    else
        return 8;
}

function checkStrong(sPW){
    if (sPW.length<=5)
        return 0; //密码太短
    Modes=0;
    for (i=0;i<sPW.length;i++){
        Modes|=CharMode(sPW.charCodeAt(i));
    }
    return bitTotal(Modes);
}

function keypw()
{
    var value = this.value;
    if(value.length>5 && value.length<21){
        var pwlevel = checkStrong(value);
        var ltu = '';
        var lzi = '';
        if(pwlevel == 1){
            ltu = '35%';
            lzi = '弱';
        }else if(pwlevel == 2){
            ltu = '75%';
            lzi = '中';
        }else if(pwlevel > 3){
            ltu = '90%';
            lzi = '强';
        }
        $('#pwlevel').css('width',ltu);
        $('#pwlevel2').html(lzi);
        pwcheck = false;
    }else{
        if( 0< value.length <6){
            $('#pwok').css('display','none');
            $('#pwlevel').css('width','0%');
            $('#pwlevel2').html('');
        }
    }
}